package team.seekers.hula.course.resource.exam.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import team.seekers.hula.common.entity.PageResult;
import team.seekers.hula.common.entity.result.ApiExceptionEnum;
import team.seekers.hula.common.utils.AssertUtils;
import team.seekers.hula.common.utils.BaseConvertUtils;
import team.seekers.hula.course.resource.exam.dao.ExamDao;
import team.seekers.hula.course.resource.exam.entity.dao.ExamDO;
import team.seekers.hula.course.resource.exam.entity.dto.ExamDTO;
import team.seekers.hula.course.resource.exam.entity.dto.ExamPageListReqDTO;
import team.seekers.hula.course.resource.exam.entity.dto.ExamProblemDTO;
import team.seekers.hula.course.resource.exam.entity.vo.ExamInfoVO;
import team.seekers.hula.course.resource.exam.entity.vo.ExamListVO;
import team.seekers.hula.course.resource.exam.entity.vo.ExamPageListVO;
import team.seekers.hula.course.resource.exam.entity.vo.ExamProblemManageListVO;
import team.seekers.hula.course.resource.problem.entity.dto.ProblemDTO;
import team.seekers.hula.course.resource.problem.service.ProblemService;
import team.seekers.hula.user.user.entity.dto.UserInfoDTO;
import team.seekers.hula.user.user.service.UserService;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * date: 2022/5/12 16:03
 *
 * @author GH
 * QQ 1124813753
 */
@Service
public class ExamManageService {

    @Autowired
    private ExamDao examDao;

    @Autowired
    private UserService userService;

    @Autowired
    private ProblemService problemService;


    @Transactional(rollbackFor = Exception.class)
    public void save(ExamDTO examDTO) {
        ExamDO examDO = new ExamDO();
        BeanUtils.copyProperties(examDTO,examDO);
        examDO.setProblems(BaseConvertUtils.objectListToBytes(examDTO.getProblems()));

        // 计算总分
        Integer totalScore = 0;
        for (ExamProblemDTO problem : examDTO.getProblems()) {
            totalScore += problem.getCriteria();
        }
        examDO.setTotalScore(totalScore);
        examDao.save(examDO);
//        List<Long> examIds = examDao.lambdaQuery().select(
//                ExamDO::getId,
//                ExamDO::getTitle
//        ).eq(ExamDO::getCtId, examDTO.getCtId()).orderByAsc(ExamDO::getGmtCreate).list()
//                .stream().map(ExamDO::getId).collect(Collectors.toList());
//
//        chapterClient.update(ChapterManageDTO.builder()
//                .id(examDTO.getCtId()).exams(examIds).build());
    }

    public void update(ExamDTO examDTO) {
        ExamDO examDO = new ExamDO();
        BeanUtils.copyProperties(examDTO,examDO);
        examDO.setProblems(BaseConvertUtils.objectListToBytes(examDTO.getProblems()));
        // 计算总分
        Integer totalScore = 0;
        for (ExamProblemDTO problem : examDTO.getProblems()) {
            totalScore += problem.getCriteria();
        }
        examDO.setTotalScore(totalScore);
        examDao.updateById(examDO);
    }

//    public List<ExamQueryDTO> queryDetailCourseExamsByChapterId(String chapterId) {
//        List<ExamDO> exams = examDao.lambdaQuery().select(
//                ExamDO::getId,
//                ExamDO::getTitle,
//                ExamDO::getDescription
//        ).eq(ExamDO::getChapterId, chapterId).list();
//
//        ArrayList<ExamQueryDTO> examQueryDTOS = new ArrayList<>();
//        for (ExamDO exam : exams) {
//            ExamQueryDTO examDTO = new ExamQueryDTO();
//            BeanUtils.copyProperties(exam,examDTO);
//            examDTO.setProblems(BaseConvertUtils.bytesToObjectList(exam.getProblems()));
//            examQueryDTOS.add(examDTO);
//        }
//        return examQueryDTOS;
//    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(String examId) {
        examDao.removeById(examId);
    }

    public PageResult<ExamPageListVO> page(ExamPageListReqDTO reqDTO) {
        Page<ExamDO> page = examDao.lambdaQuery()
                .likeRight(ExamDO::getTitle, reqDTO.getTitle())
                .page(new Page<>(reqDTO.getPageNow(), reqDTO.getPageSize()));

        List<ExamDO> examDOList = page.getRecords();
        if(examDOList.size() < 1){
            return new PageResult<>();
        }

        // 获取所有创建者name集合
        ArrayList<String> userIds = new ArrayList<>();
        for (ExamDO examDO : examDOList) {
            userIds.add(examDO.getUserId());
        }
        AssertUtils.isTrue(userIds.size() > 0, ApiExceptionEnum.UNKNOWN_ERROR,"创建者id为空");
        Map<String, UserInfoDTO> longUserBasicInfoDTOMap = userService.userIdsToUserInfoDTOs(userIds);


        ArrayList<ExamPageListVO> examPageListVOS = new ArrayList<>();
        for (ExamDO examDO : examDOList) {
            ExamPageListVO examPageListVO = new ExamPageListVO();
            BeanUtils.copyProperties(examDO,examPageListVO);
            examPageListVO.setUsername(longUserBasicInfoDTOMap.get(examDO.getUserId()).getNickname());
            examPageListVOS.add(examPageListVO);
        }
        return new PageResult<>(page.getPages(),examPageListVOS);
    }

    public List<ExamListVO> list(String title) {
        Page<ExamDO> page = examDao.lambdaQuery()
                .likeRight(ExamDO::getTitle, title)
                .page(new Page<>(1, 10));

        List<ExamDO> examDOList = page.getRecords();
        if(examDOList.size() < 1){
            return new ArrayList<>();
        }

        ArrayList<ExamListVO> examPageListVOS = new ArrayList<>();
        for (ExamDO examDO : examDOList) {
            ExamListVO examListVO = new ExamListVO();
            BeanUtils.copyProperties(examDO,examListVO);
            examPageListVOS.add(examListVO);
        }
        return examPageListVOS;
    }

    public ExamInfoVO getInfoVO(String examId) {
        ExamDO examDO = examDao.getById(examId);
        ExamInfoVO examInfoVO = new ExamInfoVO();
        BeanUtils.copyProperties(examDO,examInfoVO);


        List<ExamProblemDTO> examProblems = BaseConvertUtils.bytesToObjectList(examDO.getProblems());
        ArrayList<String> problemIds = new ArrayList<>();
        for (ExamProblemDTO examProblemDTO : examProblems) {
            problemIds.add(examProblemDTO.getId());
        }
        Map<String, ProblemDTO> longProblemDTOMap = problemService.idsMapDTO(problemIds);

        ArrayList<ExamProblemManageListVO> examProblemManageListVOS = new ArrayList<>();
        for (ExamProblemDTO examProblem : examProblems) {
            ExamProblemManageListVO examProblemManageListVO = new ExamProblemManageListVO();
            BeanUtils.copyProperties(examProblem,examProblemManageListVO);
            examProblemManageListVO.setDescription(longProblemDTOMap.get(examProblem.getId()).getDescription());
            examProblemManageListVOS.add(examProblemManageListVO);
        }

        examInfoVO.setProblems(examProblemManageListVOS);
        return examInfoVO;
    }
}
